package sword_to_1;

import java.util.Arrays;
import java.util.PriorityQueue;

public class LeeCode_40_timeout {
    public static void main(String[] args) {
        System.out.println(Arrays.toString(getLeastNumbers(new int[]{1, 2, 3}, 2)));
        System.out.println(Arrays.toString(getLeastNumbers(new int[]{0,1,2,1}, 1)));
    }
    private static int[] getLeastNumbers(int[] arr, int k) {
        if (k == 0){
            return new int[0];
        }
        PriorityQueue<Integer> queue = new PriorityQueue<>((o1, o2) -> o2 - o1);
        for (int num : arr) {
            if (queue.size() < k){
                queue.add(num);
            }else {
                if (num < queue.peek()){
                    queue.poll();
                    queue.add(num);
                }
            }
        }
        int[] ans = new int[k];
        int i = 0;
        while (!queue.isEmpty()){
            ans[i++] = queue.poll();
        }
        return ans;
    }
}
